<?php

/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/9/13
 * Time: 4:02 PM
 * To change this template use File | Settings | File Templates.
 */
class SiteController extends Controller {

    public function accessRules() {
        return array();
    }

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function actions() {
        return array();
    }

    public function  actionIndex() {
        $deals = array();
        $total = 0;
        $pages = array();

        if (isset($_GET['keywords'])) {

            $criteria = new CDbCriteria();
            $criteria->select = '*';
            $criteria->condition = 'name like :name';
            $criteria->limit = 20;
            $criteria->params = array('name' => '%' . trim($_GET['keywords']) . '%');

            $total = Deal::model()->count($criteria);

            $pages = new CPagination($total);

            $pages->pageSize = 20;

            $pages->applyLimit($criteria);

            $deals = Deal::model()->findAll($criteria);
        }
        $this->render('index', array(
            'model' => $deals,
            'item_count' => $total,
            'pages' => $pages,
            'page_size' => 20,
        ));
    }

    public function  actionGet() {
        $root_url = "http://www.staples.com/Clearance-Deals-Technology/cat_CL211635";
        $dom = new simple_html_dom();
        $dom->load(HSCommon::curl($root_url));
        $results = array();
        if ($dom == null) return;
        $page_wrapper = $dom->find('div[class="perpage"]', 0);
        if ($page_wrapper == null) {
            $limit_page = 1;
        } else {
            $arr_li = $page_wrapper->find('li');
            if (count($arr_li) >= 1) {
                end($arr_li);
                $key = key($arr_li);
                $li = $arr_li[$key - 1];
                $li_dom = new simple_html_dom();
                $li_dom->load($li);
                $limit_page = trim($li_dom->plaintext);
            } else {
                $limit_page = 1;
            }
        }

        for ($i = 1; $i <= $limit_page; $i++) {
            $url = $root_url . "?pagenum=$i";
            $dom = new simple_html_dom();
            $dom->load(HSCommon::curl($url));

            if ($dom == null) continue;
            $ul = $dom->find('ul[id="productDetail"]', 0);
            if ($ul == null) continue;
            $li = $ul->find('li');

            foreach ($li as $item) {
                //handle price
                $price_wrapper = $item->find('i[class="price"]', 0);
                if ($price_wrapper == null) continue;
                $price = trim(str_replace('*', '', $price_wrapper->plaintext));

                $pwas = $item->find('dd[class="pwas"]', 0);
                if ($pwas != null) {
                    $old_price = $pwas->find('del', 0);
                    if ($old_price != null) {
                        $old_price = trim($old_price->plaintext);
                        $price = "<span>$price </span> <span><del>$old_price</del></span>";
                    }
                }

                //handle name
                $name_wrapper = $item->find('div[class="name"]', 0);
                if ($name_wrapper == null) continue;
                $name_wrapper = $name_wrapper->find('a', 0);
                if ($name_wrapper == null) continue;
                $name = trim($name_wrapper->plaintext);

                $link = preg_match('/www.staples.com/', $name_wrapper->href) ? $name_wrapper->href : "http://www.staples.com" . $name_wrapper->href;

                //handle image
                $img = $item->find('img[class="photo"]', 0);

                $deal = new Deal();
                $deal->name = $name;
                $deal->url = $link;
                $deal->price = $price;
                $deal->picture = $img == null ? "" : $img->src;
                $deal->created_date = date('d-m-Y');
                $deal->type = DealTypeEnum::staples;

                $old_deal = Deal::model()->findByAttributes(array(
                    'name' => $deal->name,
                    'created_date' => $deal->created_date,
                    'type' => $deal->type
                ));

                if ($old_deal != null) continue;

                if ($deal->save()) {
                    array_push($results, $deal);
                }
            }
        }
        if (count($results) > 0 && count($results) > Yii::app()->params['limit']) {
            $html = '';
            $html .= '<table style="width:100%;" border="1">';
            $html .= '<tr>';
            $html .= '<th>Picture</th>';
            $html .= '<th>Name</th>';
            $html .= '<th>Price</th>';
            $html .= '<th>Link</th>';
            $html .= '</tr>';
            foreach ($results as $result) {

                $html .= '<tr>';
                if ($result->picture != '') {
                    $html .= '<td style="text-align:center"><img style="max-width: 100px; max-height: 100px" alt="" src="' . $result->picture . '"/> </td>';
                } else {
                    $html .= '<td> </td>';
                }
                $html .= '<td> ' . $result->name . '</td>';
                $html .= '<td>' . $result->price . '</td>';
                $html .= '<td><a href="' . $result->url . '">Link</a></td>';
                $html .= '</tr>';

            }
            $html .= '</table>';
            Mailer::sendEmail('nguyenhuusang90@gmail.com', "Staple's deals", $html);
//            Mailer::sendEmail(Yii::app()->params['small_email'], "Staple's deals", $html);
        } else {
            foreach ($results as $k => $result) {
                if ($k > 5) break;
                $html = '';
                $html .= '<p>';
                $html .= "<div>Name: " . $result->name . "</div>";
                $html .= "<div>Price: " . $result->price . "</div>";
                $html .= "<div><a href=" . $result->url . ">Link</a></div>";
                $html .= '</p>';
                Mailer::sendEmail('nguyenhuusang90@gmail.com', "Staple's deals", $html);
//                Mailer::sendEmail(Yii::app()->params['small_email'], "$result->name | $result->price", $html);
            }
        }
    }

    public function actionDistinct() {
        $deals = Deal::model()->findAll();
        foreach ($deals as $deal) {
            $items = Deal::model()->findAllByAttributes(array('name' => $deal->name), array('order' => ' id ASC'));
            if (count($items) == 0) continue;
            foreach ($items as $k => $item) {
                if ($k != count($items) - 1) {
                    $item->delete();
                }
            }
        }
    }

}